package Search;

import Data.GroupFriendData;

import java.io.*;
import java.nio.file.Files;
import java.sql.*;
import java.util.ArrayList;

public class SearchFriendFromGroup {
    private String group_id;
    String url = "jdbc:mysql://127.0.0.1:3306/nox?useUnicode=true&characterEncoding=UTF-8&userSSL=false&serverTimezone=GMT%2B8";
    String user = "root";
    String password = "Mi20030610.";

    public ArrayList<GroupFriendData> getFriendListFromGroup() throws ClassNotFoundException, SQLException, IOException {
        ArrayList<GroupFriendData> list=new ArrayList<>();
        //先找聊天的所有人在群聊里面的id号
        String sql="select *from group_identity_list where group_id=? order by identity asc;";
        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection Conn = DriverManager.getConnection(url, user, password);

        PreparedStatement operation=Conn.prepareStatement(sql);
        operation.setString(1,group_id);

        ResultSet resultSet=operation.executeQuery();
        while(resultSet.next())
        {
            //得到身份
            GroupFriendData e=new GroupFriendData();
            e.setIdentity(resultSet.getInt("identity"));
            e.setId(resultSet.getString("id"));

            list.add(e);

            System.out.println("找到了在"+group_id+"的好友"+e.getId()+"身份为"+e.getIdentity());
        }

        sql="select *from userinformation where id=?;";

        operation=Conn.prepareStatement(sql);
        for (int i = 0; i < list.size(); i++) {
            operation.setString(1,list.get(i).getId());

            resultSet=operation.executeQuery();
            if(resultSet.next())
            {
                list.get(i).setUserNickName(resultSet.getString("userNickName"));

                String path=resultSet.getString("avatar");
                File file=new File(path);

                byte[] t=null;
                if(file!=null)
                {
                    byte[] buffer=new byte[1024];
                    t=new byte[(int)file.length()];
                    InputStream is= Files.newInputStream(file.toPath());
                    ByteArrayOutputStream bos=new ByteArrayOutputStream();
                    int len;
                    while((len=is.read(buffer))!=-1)
                    {
                        bos.write(buffer,0,len);
                    }
                    t=bos.toByteArray();
                }
                list.get(i).setAvatar(t);
            }
        }
        return list;
    }

    public SearchFriendFromGroup(String group_id) {
        this.group_id = group_id;
    }

    public String getGroup_id() {
        return group_id;
    }

    public void setGroup_id(String group_id) {
        this.group_id = group_id;
    }
}
